<template>
    <div class="app-container"> 
        <el-form :inline="true" :model="query_form" size="mini"> 
            <el-form-item label="活动名称">
                <el-input v-model="query_form.activity_name" placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item label="活动时间" size="mini">
                <el-col :span="11">
                <el-date-picker type="date" placeholder="选择日期" v-model="query_form.start_time" style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col class="line" :span="2" style="text-align:center;">-</el-col>
                <el-col :span="11">
                <el-date-picker type="date" placeholder="选择日期" v-model="query_form.end_time" style="width: 100%;"></el-date-picker>
                </el-col>
            </el-form-item>
            <el-form-item label="活动状态" size="mini">
                <el-select v-model="query_form.state" placeholder="请选择活动状态">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="未开始" value="0"></el-option>
                    <el-option label="进行中" value="1"></el-option>
                    <el-option label="已结束" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="btnloading" @click="getlistdata(true)" circle icon="el-icon-search"></el-button>
                <el-button type="primary" @click="create_new_activity()" icon="el-icon-circle-plus-outline" circle></el-button>
            </el-form-item>
            </el-form>
 
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
                header-cell-class-name="tableheader">
        <el-table-column align="center" label="活动名称" width="100">
          <template slot-scope="scope">
            {{ scope.row.activity_name }}
          </template>
        </el-table-column> 
        <el-table-column align="center" label="活动时间" width="270">
          <template slot-scope="scope">
            {{ scope.row.start_time.substring(0,16) }} ~ {{ scope.row.end_time.substring(0,16) }}
          </template>
        </el-table-column>   

        <el-table-column align="center" label="地址">
          <template slot-scope="scope">
            {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}{{ scope.row.address }}
          </template>
        </el-table-column> 
        <el-table-column align="center" label="是否节日" width="70">
          <template slot-scope="scope">
            {{ scope.row.is_festival ==true?'是':'否' }}
          </template>
        </el-table-column> 
        <el-table-column align="center" label="状态" width="70">
          <template slot-scope="scope">
            {{ scope.row.activity_state_str }}
          </template>
        </el-table-column> 
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope"> 
            <el-button type="primary" size="mini" @click="openedit(scope.row)" icon="el-icon-edit">{{scope.row.state!='2'?"开始总结":"变更总结"}}</el-button>
            
            <el-dropdown trigger="click">
              <el-button size="mini" type="primary">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            <el-dropdown-menu slot="dropdown">
                <!-- <el-dropdown-item>
                  <el-button type="primary" size="mini" @click="create_replenishment(scope.row)" icon="el-icon-edit">补货</el-button>
                </el-dropdown-item> -->
                <el-dropdown-item>
                  <el-button type="primary" size="mini" @click="create_replenishment_excel(scope.row)" icon="el-icon-download">根据当前活动生成补货单</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" size="mini" @click="out_now_activity_excel(scope.row)" icon="el-icon-download">导出当前活动数据</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                <el-upload
                  class="upload-demo"
                  :action="$api+'/nw/upload_material?activity_id='+scope.row.activity_id"
                  :headers="{token:token}"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove" 
                  :on-exceed="handleExceed" 
                  :show-file-list="false"
                  :on-success="handleSuccess">
                  <el-button size="mini" type="primary" icon="el-icon-upload2">导入数据</el-button> 
                </el-upload>   
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button style="margin-top:3px;" type="danger" size="mini" @click="delbtn(scope.row)" icon="el-icon-delete">删除</el-button>
                </el-dropdown-item>  
            </el-dropdown-menu>
          </el-dropdown>


           </template>
        </el-table-column>
      </el-table>
 
      <div class="pagination">
        <el-pagination
          style="text-align: center"
          layout="prev, pager, next"
          small
          :current-page="query_form.page"
          :page-size="query_form.pagesize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
      
      <el-dialog title="保存活动信息" :visible.sync="adddialog" :fullscreen="true" :close-on-click-modal="false">
        <el-form :model="add_form" ref="add_form" :rules="rule" label-width="120px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="活动名称" prop="activity_name">
                        <el-input v-model="add_form.activity_name"  placeholder="请输入活动名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="开始时间" prop="start_time">
                        <el-date-picker :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"  placeholder="请选择开始时间" v-model="add_form.start_time" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="结束时间" prop="end_time">
                        <el-date-picker :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择结束时间" v-model="add_form.end_time" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态" prop="state">
                        <el-select v-model="add_form.state" placeholder="请选择">
                            <el-option :value="0" label="未开始"></el-option>
                            <el-option :value="1" label="进行中"></el-option>
                            <el-option :value="2" label="已结束"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
         
            <el-row>
                <el-col :span="12">
                    <el-form-item label="活动地址" prop="address">
                        <el-cascader 
                            :options="pcaTextArr"
                            v-model="selectedOptions" style="width:48%">
                        </el-cascader>
                        <el-input v-model="add_form.address" style="width:48%"  placeholder="请输入详细地址"></el-input>
                    </el-form-item> 
                </el-col> 
                <el-col :span="6">
                    <el-form-item label="当日温度" prop="temperature">
                        <el-input-number v-model="add_form.temperature" :controls="false" :min="-50" :max="50" label="请记录当日温度"></el-input-number> 
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="是否节日" prop="is_festival">
                        <el-select v-model="add_form.is_festival" placeholder="请选择">
                            <el-option :value="false" label="否"></el-option>
                            <el-option :value="true" label="是"></el-option> 
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注一下" prop="remark">
                        <el-input type="textarea" v-model="add_form.remark"  placeholder="请输入活动备注"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                  <el-form-item label="持续天数" prop="activity_day">
                        <el-input-number v-model="add_form.activity_day" :controls="false" :min="1" :max="50" label="请输入活动持续天数"></el-input-number> 
                    </el-form-item>
                </el-col>
            </el-row>
            <el-container> 
                <el-main>
                    <el-tabs type="border-card" v-model="def_tab">
                        <el-tab-pane 
                          v-for="item in material_list"
                          :key="item.type_id"
                          :label="item.type_name" 
                          :name="item.type_id"  
                        >
                        <el-table :data="item.inner_list"  style="height:400px; overflow-y: scroll;">
                            <el-table-column prop="material_name" label="物料" width="140">
                            </el-table-column>
                            <el-table-column prop="material_no" label="编号" width="120">
                            </el-table-column>
                            <el-table-column prop="image_path" label="图样"> 
                                    <template slot-scope="scope">
                                        <el-image 
                                                style="width: 40px; height: 40px"
                                                :src="scope.row.image_path"
                                                :preview-src-list="[scope.row.image_path]">
                                            </el-image> 
                                    </template> 
                            </el-table-column>
                            <el-table-column prop="out_count" label="带出">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.out_count" :controls="false" :min="0"></el-input-number>
                                </template> 
                            </el-table-column>
                            <el-table-column prop="return_count" label="带回">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.return_count" :controls="false" :min="0"></el-input-number>
                                </template> 
                            </el-table-column>
                        </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-container> 
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addbtn">保存</el-button>
        </div>
      </el-dialog>  

   
      <el-dialog title="补货单" :visible.sync="replenishment_dialog" :fullscreen="true" :close-on-click-modal="false">
        <el-form :model="replenishment_form" ref="replenishment_form" :rules="replenishment_rule" label-width="120px"> 
            <el-container> 
                <el-main>
                    <el-tabs type="border-card" v-model="replenishment_def_tab">
                        <el-tab-pane 
                          v-for="item in replenishment_material_list"
                          :key="item.type_id"
                          :label="item.type_name" 
                          :name="item.type_id"  
                        >
                        <el-table :data="item.inner_list"  style="height:400px; overflow-y: scroll;">
                            <el-table-column prop="material_name" label="物料" width="140">
                            </el-table-column>
                            <el-table-column prop="material_no" label="编号" width="120">
                            </el-table-column>
                            <el-table-column prop="image_path" label="图样"> 
                                    <template slot-scope="scope">
                                        <el-image 
                                                style="width: 40px; height: 40px"
                                                :src="scope.row.image_path"
                                                :preview-src-list="[scope.row.image_path]">
                                            </el-image> 
                                    </template> 
                            </el-table-column>
                            <el-table-column prop="out_count" label="计划带出">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.out_count" :controls="false" :min="0" @change="replenishment_change(scope.row.material_id)"></el-input-number>
                                </template> 
                            </el-table-column>
                            <el-table-column prop="return_count" label="上次剩余">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.return_count" :controls="false" :min="0" @change="replenishment_change(scope.row.material_id)"></el-input-number>
                                </template> 
                            </el-table-column>
                            <el-table-column prop="need_count" label="应补数量">
                                <template slot-scope="scope">
                                    <el-input-number v-model="scope.row.need_count" :controls="false"></el-input-number>
                                </template> 
                            </el-table-column>
                        </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-container> 
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="replenishment_create_btn">生成PDF</el-button>
        </div>
      </el-dialog>  
 
    </div>
  </template> 
  <script>  
  import { pcaTextArr } from 'element-china-area-data'
  import * as imageConversion from 'image-conversion' 
  import Cookies from 'js-cookie';
  export default { 
    data() {
      return { 
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        token:Cookies.get('crmtoken'),
        btnloading: false,  
        query_form: {
            activity_name: '',
            start_time:'',
            end_time:'',
            state:null,
            page: 1,
            pagesize: 20
        }, 
        add_form: {
            activity_id: '',
            activity_name: '', 
            start_time:null,
            end_time:null,
            province:'',
            city:'',
            district:'',
            address:'',
            temperature:null,
            is_festival:false,
            details:[],
            state:'',
            remark:'',
            activity_day:null
        },
        rule: {
          activity_name: [
            {required: true, message: '此项为必填项'},
          ], 
          start_time: [
            {required: true, message: '此项为必填项'},
          ], 
          end_time: [
            {required: true, message: '此项为必填项'},
          ], 
          state:[
            {required: true, message: '此项为必填项'},
          ], 
          address:[
            {required: true, message: '此项为必填项'},
          ]
        },
        pcaTextArr,
        selectedOptions:[],
        list: null,
        alllist: null,
        total: 0,
        listLoading: true,
        adddialog: false,
        editdialog: false,
        addicondia: false,
        editicondia: false,
        material_list:[],
        def_tab:'',
        replenishment_dialog:false,
        replenishment_activity_id:'',
        replenishment_material_list:[
          {
            type_id:'',
            type_name:'',
            inner_list:[
              {
                image_path:'',
                material_id:'',
                material_name:'',
                material_no:'',
                nw_type_id:'',
                out_count:0,
                return_count:0,
                need_count:0
              }
            ]
          }
        ],
        replenishment_def_tab:'',
        replenishment_form:{
          details:[]
        },
        replenishment_rule:{},
        fileList:[]
      };
    }, 
    created() {   
      this.getlistdata();
      this.get_simple_material();
    },
    methods: {
      getlistdata(isquery) {
        this.listLoading = true;
        if (isquery === true) {
          this.query_form.page = 1
        }
        this.$post(this.$api + '/nw/get_nw_activity_pagelist',this.query_form, false, this)
          .then((res) => {
            this.listLoading = false;
            if (res.code === 0) {
              this.list = res.rows;
              this.total = res.total;
            } else {
              this.$notify({
                title: '失败',
                message: res.msg,
                type: 'error'
              });
            }
          });
      }, 
      addbtn() {  
        this.$refs["add_form"].validate((valid) => {
          if (valid) {
            //验证通过开始处理符合条件的数据
            this.listLoading = true;
            this.add_form.province = this.selectedOptions[0];
            this.add_form.city = this.selectedOptions[1];
            this.add_form.district = this.selectedOptions[2];
            var sub_material_details = [];
            this.material_list.forEach(s=>{
                s.inner_list.forEach(x=>{
                    var item = {};
                    item.material_id =x.material_id;
                    item.out_count =x.out_count;
                    item.return_count =x.return_count;
                    sub_material_details.push(item);
                });
            }); 
            this.add_form.details  = sub_material_details;
            this.$post(this.$api + '/nw/save_activity', this.add_form)
            .then((res) => {
                this.listLoading = false;
                if (res.code === 0) {
                this.$notify({
                    title: '成功',
                    message: res.msg,
                    type: 'success'
                });
                this.adddialog = false;
                this.add_form = { 
                    activity_id: '',
                    activity_name: '', 
                    start_time:null,
                    end_time:null,
                    province:'',
                    city:'',
                    district:'',
                    address:'',
                    temperature:null,
                    is_festival:false,
                    details:[],
                    state:'',
                    remark:'',
                    activity_day:null
                };
                this.material_list.forEach(s=>{
                    s.inner_list.forEach(x=>{ 
                        x.out_count = 0;
                        x.return_count =0;
                    });
                });   
                this.selectedOptions=[];
                this.getlistdata(); 
                } else {
                this.$notify({
                    title: '失败',
                    message: res.msg,
                    type: 'error'
                });
                }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        }); 
      },
      openedit(item) {
            this.adddialog = true;
            for(var i in this.add_form)
            { 
                 this.add_form[i] = item[i];  
            }
            this.selectedOptions=[];
            this.selectedOptions.push(item.province);
            this.selectedOptions.push(item.city);
            this.selectedOptions.push(item.district);    
            this.$get(this.$api+"/nw/get_activity_model",{'activity_id':item.activity_id}).then(res=>{
              if(res.code ==0)
              {
                this.material_list.forEach(s=>{
                  s.inner_list.forEach(x=>{
                        res.data.details.forEach(z=>{
                            if(z.material_id == x.material_id)
                            {
                              x.return_count = z.return_count;
                              x.out_count = z.out_count;
                              return;
                            }
                        });
                    });
                });  
                 if(this.material_list.length>0)
                 {  
                    this.def_tab = this.material_list[0].type_id;
                 }
              }
              else{
                this.$notify({
                  title: '失败',
                  message: res.msg,
                  type: 'error'
                });
              }
            });  
      }, 
      create_replenishment(item){ 
        this.replenishment_activity_id = item.activity_id;
        this.$get(this.$api+"/nw/get_activity_model",{'activity_id':item.activity_id}).then(res=>{
          this.replenishment_dialog = true;
              if(res.code ==0)
              {
                this.replenishment_material_list.forEach(s=>{
                  s.inner_list.forEach(x=>{
                        res.data.details.forEach(z=>{
                            if(z.material_id == x.material_id)
                            {
                              x.return_count = z.return_count;
                              x.out_count = z.out_count;
                              x.need_count = x.out_count-x.return_count;
                              return;
                            }
                        });
                    });
                });  
                 if(this.replenishment_material_list.length>0)
                 {  
                    this.replenishment_def_tab = this.replenishment_material_list[0].type_id;
                 }
              }
              else{
                this.$notify({
                  title: '失败',
                  message: res.msg,
                  type: 'error'
                });
              }
            });  
      },
      replenishment_btn(){

      },
      delbtn(item) {
        this.$confirm('确认删除？?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$get(this.$api + '/nw/del_activity', {
            'activity_id': item.activity_id
          })
            .then((res) => {
              this.listLoading = false;
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: res.msg,
                  type: 'success'
                });
                this.getlistdata();
              } else {
                this.$notify({
                  title: '失败',
                  message: res.msg,
                  type: 'error'
                });
              }
            });
        })
      },
      handleSizeChange(v) {
        this.form.pagesize = v;
        this.getlistdata();
      },
      handleCurrentChange(v) {
        this.form.page = v;
        this.getlistdata();
      },
      get_simple_material(){
        //获取所有库存信息
        this.$get(this.$api+"/nw/get_material_all_list").then(res=>{
            if (res.code === 0) { 
                 this.material_list = res.data; 
                 this.replenishment_material_list = res.data;
                 if(res.data.length>0)
                 { 
                    this.def_tab = res.data[0].type_id;
                    this.replenishment_material_def_tab= res.data[0].type_id;
                 }
              } else {
                this.$notify({
                  title: '获取物料信息异常',
                  message: res.msg,
                  type: 'error'
                });
              }
        });
      },
      handleClick(tab,event){ 

      },
      replenishment_change(material_id){
          var next_change = 0;
          this.replenishment_material_list.forEach(s=>{
            s.inner_list.forEach(x=>{
              if(x.material_id == material_id)
              { 
                console.log(x);
                 x.need_count = x.out_count-x.return_count;
                 return;
              } 
            }); 
          });
      },
      replenishment_create_btn()
      { 
          var sub_data = {};
          sub_data.activity_id =  this.replenishment_activity_id; 
          sub_data.record_list = this.replenishment_material_list;
          this.$post(this.$api + '/nw/start_replenishment',sub_data, false, this)
          .then((res) => {
            this.listLoading = false;
            if (res.code === 0) {
              this.$notify({
                  title: '这里成功了 我该跳转了 现在就去做了',
                  message: res.msg,
                  type: 'success'
                });
            } else {
              this.$notify({
                title: '失败',
                message: res.msg,
                type: 'error'
              });
            }
          }); 
      },
      create_new_activity(){
        this.adddialog=true; 
        this.add_form = { 
                    activity_id: '',
                    activity_name: '', 
                    start_time:null,
                    end_time:null,
                    province:'',
                    city:'',
                    district:'',
                    address:'',
                    temperature:null,
                    is_festival:false,
                    details:[],
                    state:'',
                    remark:''
                };
                this.material_list.forEach(s=>{
                    s.inner_list.forEach(x=>{ 
                        x.out_count = 0;
                        x.return_count =0;
                    });
                });   
                this.selectedOptions=[];
      },
      create_replenishment_excel(row){
        this.$downloadpost(this.$api + '/nw/out_material_list_excel', {
          activity_id:row.activity_id
        }, false);
      },
      out_now_activity_excel(row){
        this.$downloadpost(this.$api + '/nw/out_now_activity_excel', {
          activity_id:row.activity_id
        }, false);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.fileList = [];
        //this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleSuccess(res,file,fileList)
      {
        console.log(res); 
        if(res.code == 0)
        {
          this.$notify({
                  title: '处理成功',
                  message: res.msg,
                  type: 'success'
                }); 
       }
       else{
        this.$notify({
                  title: '处理失败',
                  message: res.msg,
                  type: 'error'
                });
       }
      }
    }
  };
  </script>
  
  